package com.deyuanyun.pic.settings.service.msgtemplate;

import com.alibaba.fastjson.JSONObject;
import com.deyuanyun.pic.common.util.CommonUtil;
import com.deyuanyun.pic.common.util.DateUtil;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.settings.controller.dto.BizMsgThresholdVO;
import com.deyuanyun.pic.settings.controller.dto.base.DefectInfoDTO;
import com.deyuanyun.pic.settings.domain.base.BizMsgUser;
import com.deyuanyun.pic.settings.enumeration.ThresholdType;
import com.deyuanyun.pic.settings.service.msgtemplate.pbf.DefectNoticePushMsg;
import com.deyuanyun.pic.settings.support.utils.CronUtils;
import com.deyuanyun.pic.settings.task.DefectNoticeTask;
import com.deyuanyun.pic.settings.task.QuartzConsts;
import com.deyuanyun.pic.settings.task.SchedulerJob;
import com.deyuanyun.pic.settings.task.util.QuartzManagerUtil;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  内检测评价新增与更新录入消息推送
 *  @author axiao(xj08.dream@gmail.com)
 *  @date 2016-08-10
 *  @version 1.0
 *  Histroy: [修改人][时间][描述]
 */
public class InspAppraisePushMsg extends AbstractPushMsgTemplate {

    protected static final Logger LOGGER = LoggerFactory.getLogger(InspAppraisePushMsg.class);

    /** 缺陷评价任务id key */
    public static final String TASK_ID_KEY = "taskId";
    /** 缺陷id key */
    public static final String DEFECT_ID_KEY = "defectId";

    @Override
    public void doPushMsgData() {
        if(!super.isInterface) { //当是否接口调用为false的时候不允许向下执行
            LOGGER.info("不是接口调用，不允许执行");
            return;
        }
        if(super.interfaceParam.isEmpty()) {
            LOGGER.info("没有传入接口参数");
            return;
        }
        Map<String, Object> interfaceMap = super.interfaceParam;
        Object taskIdObj = interfaceMap.get(this.TASK_ID_KEY);
        Object defectIdObj = interfaceMap.get(this.DEFECT_ID_KEY);
        if(taskIdObj == null || defectIdObj == null) {//其中任务参数任何一个为空都不允许向下执行
            LOGGER.info("接口调用所需要的缺陷id和检测认为id必须都有值");
            return;
        }

        Map<String, Object> taskInfo = super.bizMsgThresholdService.findEvaluationTaskInfo(taskIdObj.toString());
        if(taskInfo == null){
            LOGGER.error("没有查询到检测任务信息");
            return;
        }
        Object nameObj = taskInfo.get("NAME");
        if(nameObj == null) {
            LOGGER.error("没有找到检测任务名称");
            return;
        }
        BizMsgThresholdVO inspInputAppraise = bizMsgThresholdService.queryDataByTypeOne(ThresholdType.INTERNAL_INSP_INPUT_APPRAISE.getValue());
        //提醒所有用户内检数据评价已更新
        super.thresListCastString(Lists.newArrayList(nameObj.toString()));
        initializeBizMsgSends(inspInputAppraise);

        List<String> defectIds = (List<String>) defectIdObj;

        if(defectIds == null || defectIds.isEmpty()) {
            if(LOGGER.isInfoEnabled()) {
                LOGGER.info("接口调用没有传入缺陷点数据");
            }
            return;
        }

        DefectInfoDTO defectInfoDTO = super.bizMsgThresholdIntefaceService.queryTheFirstDefect(defectIds);
        BizMsgThresholdVO defectNotice = bizMsgThresholdService.queryDataByTypeOne(ThresholdType.INTERNAL_INSP_DEFECT_NOTICE_SCHEDULE.getValue());

        if(defectNotice != null && defectInfoDTO != null) {
            JSONObject jsonObject = JSONObject.parseObject(defectNotice.getThresholdContent());
            int day = jsonObject.getIntValue("day"); //提前多少天开始通知

            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put(DefectNoticePushMsg.DEFECT_INFO_DTO, defectInfoDTO);//放入缺陷实体类信息
            dataMap.put(DefectNoticePushMsg.DEFECT_NOTICE, defectNotice); //放入缺陷通知业务阀值实体类信息
            String name = defectInfoDTO.getId() + defectInfoDTO.getPipeLineId() + defectInfoDTO.getMileage();//任务名为：缺陷id+管道id+绝对距离
            if (StringUtils.isNotEmpty(name)) {
                Date pushDate = DateUtil.getDateForBefore(defectInfoDTO.getPlanRepairTime(), day);
                Date n =  CronUtils.getDefectNoticeCron(pushDate);
                if(LOGGER.isInfoEnabled()) {
                    LOGGER.info("当前的任务名为：" + name);
                    LOGGER.info("当前缺陷的最迟维修时间为：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(defectInfoDTO.getPlanRepairTime()));
                    LOGGER.info("当前提醒时间为：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(n));
                }
                //创建任务
                SchedulerJob schedulerJob = new SchedulerJob(name, QuartzConsts.INSP_DEFECT_NOTICE_GROUP_NAME, n, DefectNoticeTask.class, dataMap);
                QuartzManagerUtil.addJobStartByDate(schedulerJob);
            }
        }
    }


    /**
     * @param args 参数说明：
     * <pre>
     * arg[0]：为业务阀值实体信息，类型为：{@link BizMsgThresholdVO}<br />
     * </pre>
     */
    @Override
    public void initializeBizMsgSends(Object... args) {
        BizMsgThresholdVO inspInputAppraise = (BizMsgThresholdVO) args[0];
        //提醒所有用户内检数据评价已更新
        BizMsgUser bizMsgUser = new BizMsgUser();
        bizMsgUser.setId(CommonUtil.getUUID());
        bizMsgUser.setMsgContent(inspInputAppraise.getMsgContent());
        bizMsgUser.setCreateDate(new Date());
        bizMsgUser.setCreateRemark("内检测评价结果录入消息推送");
        if (StringUtils.isNotEmpty(super.thresholdContent)) { //设置阀值内容
            bizMsgUser.setThresholdContent(super.thresholdContent);
        }

        List<MsgQueue.BizMsgUserInfo> userInfos = new ArrayList<MsgQueue.BizMsgUserInfo>();
        userInfos.add(msgQueue.new BizMsgUserInfo().setValid(false).setBizMsgUser(bizMsgUser));

        MsgQueue.MsgInfo msgInfo = msgQueue.new MsgInfo().setBizMsgThresholdId(inspInputAppraise.getId())
                .setThresholdSet(inspInputAppraise.getThresholdContent());
        msgQueue.addOperator(msgQueue.new PushMsgOperator(userInfos, msgInfo));
    }

    @Override
    public boolean valiIsPush(Map<String, Object> valiMap) {
        return false;
    }
}
